<template>
  <div class="photographer-portfolio-container">
    <el-card class="portfolio-card">
      <!-- 摄影师信息 -->
      <div class="photographer-info">
        <el-avatar :size="80" :src="photographer?.avatar" />
        <div class="info-content">
          <h3>
            {{ photographer?.nickname }}
            <span :class="['level-tag', `level-${photographer?.level}`]">
              {{ getLevel(photographer?.level) }}
            </span>
          </h3>
          <p class="introduction">{{ photographer?.introduction }}</p>
          <!-- <div class="specialties">
            <el-tag
              v-for="specialty in photographer?.specialties"
              :key="specialty"
              class="specialty-tag"
              size="small"
            >
              {{ specialtiesMap[specialty] }}
            </el-tag>
          </div> -->
          <div class="stats">
            <span>作品数: {{ photographer?.samples_count }}</span>
            <span style="margin-left: 60px">评分: {{ photographer?.rating }}</span>
          </div>
        </div>
      </div>

      <!-- 作品列表 -->
      <div class="portfolio-grid">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" v-for="item in portfolioList" :key="item.id">
            <div class="portfolio-item" @click="handlePreview(item)">
              <div class="image-wrapper">
                <img :src="item.photos?.[0]" :alt="item.title" />
                <div class="overlay">
                  <h3>{{ item.title }}</h3>
                  <p>{{ item.description }}</p>
                  <div class="meta">
                    <span>{{ item.shooting_date }}</span>
                    <span>
                      <el-icon><Star /></el-icon>
                      {{ item.likes }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[12, 24, 36, 48]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 预览弹窗 -->
    <el-dialog
      v-model="previewVisible"
      width="80%"
      :show-close="true"
      destroy-on-close
      class="preview-dialog"
    >
      <div class="preview-content">
        <el-carousel height="70vh" arrow="always" indicator-position="outside">
          <el-carousel-item v-for="(photo, index) in currentItem?.photos" :key="index">
            <img :src="photo" class="preview-image" />
          </el-carousel-item>
        </el-carousel>
        <div class="preview-info">
          <div class="title-section">
            <h2>{{ currentItem?.title }}</h2>
            <div class="tags-container" v-if="currentItem?.tags?.length">
              <el-tag
                v-for="tag in currentItem.tags"
                :key="tag"
                class="tag-item"
                size="small"
                effect="plain"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
          <p>{{ currentItem?.description }}</p>
          <div class="preview-meta">
            <span>拍摄时间：{{ currentItem?.shooting_date }}</span>
            <el-button type="primary" size="small" @click="handleLike" :loading="likeLoading">
              <el-icon><Star /></el-icon>
              {{ currentItem?.is_liked ? '已点赞' : '点赞' }} {{ currentItem?.likes }}
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Star } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getPhotographerDetail } from '@/api/photographer'
import { getSamplesList, getSamplesPublicList, likeSample, unlikeSample } from '@/api/sample'
import type { Sample } from '@/types/sample'
import type { Photographer } from '@/types/photographer'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const userRole = computed(() => userStore.userRole)
const isLoggedIn = computed(() => userStore.isLoggedIn)

const photographer = ref<Photographer>()
const portfolioList = ref<Sample[]>([])
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const previewVisible = ref(false)
const currentItem = ref<Sample | null>(null)
const likeLoading = ref(false)

const specialtiesMap: Record<string, string> = {
  wedding: '婚纱摄影',
  portrait: '写真',
  children: '儿童摄影',
  family: '全家福',
  maternity: '孕妇照',
}

// 获取摄影师等级
const getLevel = (level?: number) => {
  if (!level) return ''
  const labels: Record<number, string> = {
    1: '初级摄影师',
    2: '高级摄影师',
    3: '资深摄影师',
    4: '首席摄影师',
  }
  return labels[level]
}

// 获取摄影师信息
const fetchPhotographer = async () => {
  try {
    const { data } = await getPhotographerDetail(Number(route.params.id))
    photographer.value = data.data
  } catch (error) {
    ElMessage.error('获取摄影师信息失败')
  }
}

// 获取作品列表
const fetchPortfolio = async () => {
  try {
    if (!userStore.isLoggedIn) {
      const { data } = await getSamplesPublicList({
        photographer_id: Number(route.params.id),
        is_public: true,
        page: currentPage.value,
        pageSize: pageSize.value,
      })
      portfolioList.value = data.data.items
      total.value = data.data.meta.total
    } else {
      const { data } = await getSamplesList({
        photographer_id: Number(route.params.id),
        is_public: true,
        page: currentPage.value,
        pageSize: pageSize.value,
      })
      portfolioList.value = data.data.items
      total.value = data.data.meta.total
    }
  } catch (error) {
    ElMessage.error('获取作品列表失败')
  }
}

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchPortfolio()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchPortfolio()
}

// 处理预览
const handlePreview = (item: Sample) => {
  currentItem.value = item
  previewVisible.value = true
}

// 处理点赞
const handleLike = async () => {
  if (!currentItem.value) return
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }

  likeLoading.value = true
  try {
    if (currentItem.value.is_liked) {
      await unlikeSample(currentItem.value.id)
      currentItem.value.likes--
      currentItem.value.is_liked = false
      fetchPortfolio()
      ElMessage.success('已取消点赞')
    } else {
      await likeSample(currentItem.value.id)
      currentItem.value.likes++
      currentItem.value.is_liked = true
      fetchPortfolio()
      ElMessage.success('点赞成功')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    likeLoading.value = false
  }
}

// 预约摄影师
const handleBook = () => {
  router.push({
    path: '/booking',
    query: { photographer_id: route.params.id },
  })
}

onMounted(() => {
  fetchPhotographer()
  fetchPortfolio()
})
</script>

<style scoped>
.photographer-portfolio-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  min-height: calc(100vh - 200px);
  box-sizing: border-box;
}

.portfolio-card {
  margin-top: 0;
}

.photographer-info {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.info-content {
  flex: 1;
}

.info-content h2 {
  margin: 0 0 10px 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.introduction {
  margin: 10px 0;
  color: #666;
  line-height: 1.6;
}

.specialties {
  margin: 10px 0;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.stats {
  display: flex;
  gap: 20px;
  color: #666;
  margin-top: 10px;
}

.action-buttons {
  display: flex;
  align-items: center;
}

.level-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.level-1 {
  background-color: #e1f3d8;
  color: #67c23a;
}

.level-2 {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.level-3 {
  background-color: #f0f9ff;
  color: #409eff;
}

.level-4 {
  background-color: #fef0f0;
  color: #f56c6c;
}

/* 作品列表样式复用 PortfolioView 的相关样式 */
.portfolio-grid {
  margin: 20px 0;
}

.portfolio-item {
  margin-bottom: 20px;
  cursor: pointer;
}

.image-wrapper {
  position: relative;
  width: 100%;
  padding-top: 100%;
  overflow: hidden;
  border-radius: 4px;
}

.image-wrapper img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.portfolio-item:hover .image-wrapper img {
  transform: scale(1.05);
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}

.portfolio-item:hover .overlay {
  opacity: 1;
}

.overlay h3 {
  margin: 0;
  font-size: 18px;
}

.overlay p {
  margin: 10px 0;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.preview-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.preview-content {
  text-align: center;
  padding: 20px;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

.preview-info {
  margin-top: 20px;
  text-align: left;
}

.preview-meta {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.title-section h2 {
  margin: 0;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  margin: 0;
}
</style>
